var request = require('request');

class CNodeJS {
    constructor(options) {
        this.options = options || {};
        options.url = options.url || "http://127.0.0.1:3000/hw/";
    }

    baseParams(params) {
        params = Object.assign({}, params || {});
        if (this.options.token) {
            params.accesstoken = this.options.token;
        }
        return params;
    }

    request1(method, path, params) {
        return new Promise(function (resolve, reject) {
            var opts = {
                method: method.toUpperCase(),
                url: this.options.url + path,
                json: true,
            };

            if (opts.method === 'GET' || opts.method === 'HEAD') {
                opts.qs = this.baseParams(params);
            } else {
                opts.body = this.baseParams(params);
            }

            request(opts, function (err, res, body) {
                if (err) {
                    return reject(err);
                }

                if (body) {
                    // body || res.body
                    resolve(body);
                } else {
                    reject(new Error("body#error"));
                }
            });
        }.bind(this));
    }

    request2(method, path, params, callback) {
        return new Promise(function (resolve_, reject_) {
            var opts = {
                method: method.toUpperCase(),
                url: this.options.url + path,
                json: true,
            };

            if (opts.method === 'GET' || opts.method === 'HEAD') {
                opts.qs = this.baseParams(params);
            } else {
                opts.body = this.baseParams(params);
            }

            const resolve = function (res) {
                resolve_(res);
                callback && callback(null, res);
            };

            const reject = function (err) {
                reject_(err);
                callback && callback(err);
            }

            request(opts, function (err, res, body) {
                if (err) {
                    return reject(err);
                }

                if (body) {
                    // body || res.body
                    resolve(body);
                } else {
                    reject(new Error("body#error"));
                }
            });
        }.bind(this));
    }

    request3(method, path, params, callback) {
        return request2(method, path, params, callback)
            .then(function (result) {
                    Promise.resolve(result.data)
                }
            );
    }
}

var client = new CNodeJS({
    url: 'http://127.0.0.1:3000/hw/',
});

client.request2('GET', 'abc', {})
    .then(function (result) {
        console.log(result)
    })
    .catch(function (err) {
            console.error(err)
        }
    );

client.request2('GET', 'abc', {}, function (err, data) {
    console.log("" + data);
    console.log(err);
});